package com.sxdz.pay

import com.sxdz.api.webService.CalculatorDelegate
import com.sxdz.api.webService.CustomerVo
import com.sxdz.api.webService.ResultVo
import com.sxdz.api.webService.UserCardCtmCardRltVo
import com.sxdz.constant.CommonConstant
import com.sxdz.constant.GlobalConstant
import com.sxdz.constant.MessageConstant
import com.sxdz.controller.handler.CalculatorHandler
import com.sxdz.controller.handler.RequestRemoteHandler
import com.sxdz.controller.service.order.IOrderDetailService
import com.sxdz.controller.service.order.IOrderService
import com.sxdz.controller.service.wechat.IWechatSubService
import com.sxdz.models.TOrder
import com.sxdz.models.TblWechatSubscribe
import com.sxdz.models.api.PayTongzhi
import com.sxdz.models.common.JsonResult
import com.sxdz.models.common.Pay
import com.sxdz.models.common.PayRefuse
import com.sxdz.models.common.TPay
import com.sxdz.pay.util.SignUtils
import com.sxdz.pay.util.XmlUtils
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.toolbox.utils.DateUtil
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

import javax.servlet.http.HttpServletRequest
import java.text.DecimalFormat
import java.text.SimpleDateFormat

/**
 * Created by lzw on 2016/8/17.
 * 移动支付订单返回通知--威富通回调
 */
@RestController
@CompileStatic
@TypeChecked
@RequestMapping("payResult")
class PayResultApi {

    private final static String version = "2.0";
    private final static String charset = "UTF-8";
    private final static String sign_type = "MD5";

    @Autowired
    private IOrderService orderService//订单数据
    @Autowired
    private IOrderDetailService orderDetailService//订单详情
    @Autowired
    private IWechatSubService wechatSubService

    private Logger logger = LoggerFactory.getLogger(this.getClass())

    /***
     * 订单通知接口
     * @param outTradeNo
     * @param transactionId
     * @return
     */
    @RequestMapping(value = "query")
     queryResult(HttpServletRequest req) throws Exception {

        req.setCharacterEncoding("utf-8");
        String resString = XmlUtils.parseRequst(req);
        String respString = "error";
        Map<String, String> map = null;
        if (resString != null && !"".equals(resString)) {
            map = XmlUtils.toMap(resString.getBytes(), "utf-8");
            String res = XmlUtils.toXml(map);
            logger.info("======================支付通知请求接口返回*************==================：" + res);
            try {
                 if (map.containsKey("sign")) {
                     if (SignUtils.checkParam(map, GlobalConstant.getString("key"))) {
                         /**
                          * status,result_code都为0的时候代表支付成功，返回页面通知
                          */
                         String status = map.get("status");
                         if (status != null && "0".equals(status)) {//通信成功
                             String result_code = map.get("result_code");

                             if (result_code != null && "0".equals(result_code)) {// 支付成功

                                 ObjectMapper om = new ObjectMapper();
                                 om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                 //将支付完成的字符串转换成json
                                 String json = om.writeValueAsString(map)
                                 logger.info("================支付结果返回json:================" + json)
                                 //将json转换成对象的实体bean
                                 PayTongzhi resultJson = om.readValue(json, PayTongzhi.class);
                                 Map<String, Object> params = new HashMap<>()
                                 params << [outTradeNo: resultJson.out_trade_no]//根据返回的商户号进行业务更新
                                 List<TOrder> orderList = orderService.findListByParams(params, null)
                                 if (orderList != null && orderList.size() > 0) {
                                     /**
                                      * 支付成功返回的参数如下：
                                      * openid --用户在商户 appid 下的唯一标识，交易类型 trade_type
                                      是否关注公众账号--is_subscribe 0-关注，1-未关注，支付结果 --pay_result 0—成功；其它—失败
                                      支付结果信息 --pay_info支付结果信息，支付成功时为空，威富通订单号 transaction_id 威富通交易号
                                      第三方商户号 out_transaction_id ，sub_is_subscribe 0-关注，1-未关注，子商户 appid sub_appid
                                      用户 openid sub_openid,商户订单号 out_trade_no,总金额 total_fee
                                      现金券金额-- coupon_fee，货币种类 --fee_type 默认人民币：CNY
                                      附加信息 attach ，付款银行 bank_type，银行订单号 bank_billno若为微信支付则为空
                                      支付完成时间 time_end
                                      */
                                     TOrder orderInfo = orderList.get(0)
                                     Long orderId = orderInfo.id
                                     logger.info("=============支付通知查询订单表的支付状态为================：" + orderInfo.payStatus)
                                     if (!"00".equals(orderInfo.payStatus)) {

                                         //代表订单已经处理了，不需要进行发送消息
                                         respString = "success";
                                         logger.info("================成功消息已经发送不需要再次发送=====================")
                                     }else{
                                         orderInfo.payStatus = CommonConstant.PayStatus.PaySuccess.value//支付成功
                                         orderInfo.tradeType = resultJson.trade_type;
                                         orderInfo.payInfo = resultJson.pay_info
                                         orderInfo.payTime = DateUtil.time.time
                                         orderInfo.transactionId = resultJson.transaction_id
                                         orderInfo.outTransactionId = resultJson.out_transaction_id//交易流水号
                                         String totalI = resultJson.total_fee
                                         String coupon = resultJson.coupon_fee
                                         Long totalFeeI = 0l
                                         Long couponFeeI = 0l
                                         if(totalI!=null && !"".equals(totalI)){
                                             totalFeeI =  Long.valueOf(totalI)
                                         }
                                         if(coupon!=null && !"".equals(coupon)){
                                             couponFeeI = Long.valueOf(coupon)
                                         }
                                         String timeE = resultJson.time_end
                                         Long date = 0l
                                         if(timeE!=null && !"".equals(timeE)){
                                             date = Long.valueOf(timeE)
                                         }
                                         orderInfo.couponFee = couponFeeI
                                         orderInfo.feeType = resultJson.fee_type
                                         orderInfo.bankType = resultJson.bank_type
                                         orderInfo.bankBillNo = resultJson.bank_billno
                                         orderInfo.timeEnd = resultJson.time_end
                                         if("1".equals(orderInfo.goodsModule)){
                                             orderInfo.orderStatus=CommonConstant.OrderStatus.BHZ.value;
                                         }
                                         orderService.modifyBasic(orderInfo);//更新订单数据
                                         if("3".equals(orderInfo.goodsModule)){//电视维护费
/*** 调取广电充值接口返回受理流水号 */
                                             TPay pay = new TPay();
                                             DecimalFormat df = new DecimalFormat("######0.00");
                                             String total = orderInfo.payFee.toString()//传入缴费金额
                                             if(total!=null && !"".equals(total)){
                                                 pay.totalFee = df.format(Double.parseDouble(total) / 100)
                                             }else{
                                                 pay.totalFee = "0"
                                             }
                                             logger.info("===========【广电支付接口传入金额】======" + df.format(Double.parseDouble(total) / 100));
                                             pay.openId = resultJson.openid//用户唯一标识
                                             pay.appId = GlobalConstant.getString("weixin.appid")
                                             pay.reserve1=orderInfo.reserve1;
                                             pay.reserve2=orderInfo.goodsNum+"";
                                             pay.intelligentNo=orderInfo.intelligentNo;
                                             new Thread(new Runnable(){
                                                 @Override
                                                 public void run() {
                                                     setNoticeToLs(pay,resultJson.out_trade_no)
                                                 }
                                             }).run();
                                         }else{//商品类的直接发送模板消息
                                             //发送模板消息-支付成功消息
                                             Map<String,String> paramsMap=[:];
                                             String url=GlobalConstant.getString("template.msgBasic.url");
                                             url=url.replaceAll("orderId1",orderInfo.id+"");

                                             paramsMap << ["mchtId":GlobalConstant.getString("i2_mchtId")]
                                             paramsMap << ["templateId":GlobalConstant.getString("template.msg.id")]
                                             if(GlobalConstant.getString("mch_id").equals("7551000001")){
                                                 paramsMap << ["touser":orderInfo.reserve2]
                                                 url=url.replaceAll("openId2",orderInfo.reserve2);
                                             }else {
                                                 url=url.replaceAll("openId2",resultJson.openid);
                                                 paramsMap << ["touser":orderInfo.reserve2]
                                             }
                                             paramsMap << ["url": url]//链接
                                             paramsMap << ["first":GlobalConstant.getString("template.msg.pay.success.first")]
                                             paramsMap << ["keyword":(orderInfo.payFee/100).toString()+","+resultJson.attach]
                                             paramsMap << ["remark":GlobalConstant.getString("template.msg.pay.success.remark")]
                                             logger.info(GlobalConstant.getString("i2_mchtId")+"|"+GlobalConstant.getString("template.msg.id")+"|"+resultJson.openid+"|"+GlobalConstant.getString("template.msgBasic.url")+"|"+GlobalConstant.getString("template.msg.pay.success.first")+"|"+(orderInfo.payFee/100).toString()+","+resultJson.attach+"|"+GlobalConstant.getString("template.msg.pay.success.remark"))
                                             //paramsMap << ["color":""]
                                             def  result2=RequestRemoteHandler.postJson(GlobalConstant.getString("template.i2.url"),paramsMap,null,null)
                                             if (result2 == null)
                                                 logger.info("支付成功消息模板-发送消息失败请求失败[outTradeNo="+resultJson.out_trade_no+"]")
                                             else if ("00" == result2['respCode']) {
                                                 logger.info("支付成功消息模板-发送消息成功[outTradeNo="+resultJson.out_trade_no+"]")
                                             }else{
                                                 logger.info("支付成功消息模板-发送消息失败请求失败[outTradeNo="+resultJson.out_trade_no+",errorInfo="+result2['errorInfo']+"]")
                                             }
                                         }

                                         respString = "success";
                                     }
                                 }

                             }else {//支付失败
                                 //todo  更新支付失败的订单信息
                                 respString = "fail";
                             }
                             } else {
                             respString = "fail";
                         }
                     } else {
                         res = "验证签名不通过";
                         logger.info("===================验证签名不通过去验证网关和通讯标记======================")
                         String status = map.get("status");
                         if (status != null && "0".equals(status)) {//通信成功
                             String result_code = map.get("result_code");
                             if (result_code != null && "0".equals(result_code)) {
                                 ObjectMapper om = new ObjectMapper();
                                 om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                 //将支付完成的字符串转换成json
                                 String json = om.writeValueAsString(map)
                                 logger.info("================支付结果返回json:================" + json)
                                 //将json转换成对象的实体bean
                                 PayTongzhi resultJson = om.readValue(json, PayTongzhi.class);
                                 Map<String, Object> params = new HashMap<>()
                                 params << [outTradeNo: resultJson.out_trade_no]//根据返回的商户号进行业务更新
                                 List<TOrder> orderList = orderService.findListByParams(params, null)
                                 if (orderList != null && orderList.size() > 0) {
                                     /**
                                      * 支付成功返回的参数如下：
                                      * openid --用户在商户 appid 下的唯一标识，交易类型 trade_type
                                      是否关注公众账号--is_subscribe 0-关注，1-未关注，支付结果 --pay_result 0—成功；其它—失败
                                      支付结果信息 --pay_info支付结果信息，支付成功时为空，威富通订单号 transaction_id 威富通交易号
                                      第三方商户号 out_transaction_id ，sub_is_subscribe 0-关注，1-未关注，子商户 appid sub_appid
                                      用户 openid sub_openid,商户订单号 out_trade_no,总金额 total_fee
                                      现金券金额-- coupon_fee，货币种类 --fee_type 默认人民币：CNY
                                      附加信息 attach ，付款银行 bank_type，银行订单号 bank_billno若为微信支付则为空
                                      支付完成时间 time_end
                                      */
                                     TOrder orderInfo = orderList.get(0)
                                     Long orderId = orderInfo.id
                                     logger.info("=============支付通知查询订单表的支付状态为================：" + orderInfo.payStatus)
                                     if (!"00".equals(orderInfo.payStatus)) {

                                         //代表订单已经处理了，不需要进行发送消息
                                         respString = "success";
                                         logger.info("================成功消息已经发送不需要再次发送=====================")
                                     }else{
                                         orderInfo.payStatus = CommonConstant.PayStatus.PaySuccess.value//支付成功
                                         orderInfo.tradeType = resultJson.trade_type;
                                         orderInfo.payInfo = resultJson.pay_info
                                         orderInfo.payTime = DateUtil.time.time
                                         orderInfo.transactionId = resultJson.transaction_id
                                         orderInfo.outTransactionId = resultJson.out_transaction_id//交易流水号
                                         String totalI = resultJson.total_fee
                                         String coupon = resultJson.coupon_fee
                                         Long totalFeeI = 0l
                                         Long couponFeeI = 0l
                                         if(totalI!=null && !"".equals(totalI)){
                                             totalFeeI =  Long.valueOf(totalI)
                                         }
                                         if(coupon!=null && !"".equals(coupon)){
                                             couponFeeI = Long.valueOf(coupon)
                                         }
                                         String timeE = resultJson.time_end
                                         Long date = 0l
                                         if(timeE!=null && !"".equals(timeE)){
                                             date = Long.valueOf(timeE)
                                         }
                                         orderInfo.couponFee = couponFeeI
                                         orderInfo.feeType = resultJson.fee_type
                                         orderInfo.bankType = resultJson.bank_type
                                         orderInfo.bankBillNo = resultJson.bank_billno
                                         orderInfo.timeEnd = resultJson.time_end
                                         if("1".equals(orderInfo.goodsModule)){
                                             orderInfo.orderStatus=CommonConstant.OrderStatus.BHZ.value;
                                         }
                                         orderService.modifyBasic(orderInfo);//更新订单数据
                                         if("3".equals(orderInfo.goodsModule)){//电视维护费
                                             /*** 调取广电充值接口返回受理流水号 */
                                             TPay pay = new TPay();
                                             DecimalFormat df = new DecimalFormat("######0.00");
                                             String total = orderInfo.payFee.toString()//传入缴费金额
                                             if(total!=null && !"".equals(total)){
                                                 pay.totalFee = df.format(Double.parseDouble(total) / 100)
                                             }else{
                                                 pay.totalFee = "0"
                                             }
                                             logger.info("===========【广电支付接口传入金额】======" + df.format(Double.parseDouble(total) / 100));
                                             pay.openId = resultJson.openid//用户唯一标识
                                             pay.appId = GlobalConstant.getString("weixin.appid")
                                             pay.reserve1=orderInfo.reserve1;
                                             pay.reserve2=orderInfo.goodsNum+"";
                                             pay.intelligentNo=orderInfo.intelligentNo;
                                             new Thread(new Runnable(){
                                                 @Override
                                                 public void run() {
                                                     setNoticeToLs(pay,resultJson.out_trade_no)
                                                 }
                                             }).run();
                                         }else{//商品类的直接发送模板消息
                                             //发送模板消息-支付成功消息
                                             Map<String,String> paramsMap=[:];
                                             String url=GlobalConstant.getString("template.msgBasic.url");
                                             url=url.replaceAll("orderId1",orderInfo.id+"");
                                             paramsMap << ["mchtId":GlobalConstant.getString("i2_mchtId")]
                                             paramsMap << ["templateId":GlobalConstant.getString("template.msg.id")]
                                             if(GlobalConstant.getString("mch_id").equals("7551000001")){
                                                 paramsMap << ["touser":orderInfo.reserve2]
                                                 url=url.replaceAll("openId2",orderInfo.reserve2);
                                             }else{
                                                 paramsMap << ["touser":orderInfo.reserve2]
                                                 url=url.replaceAll("openId2",orderInfo.reserve2);
                                             }
                                             paramsMap << ["url":url]//链接
                                             paramsMap << ["first":GlobalConstant.getString("template.msg.pay.success.first")]
                                             paramsMap << ["keyword":(orderInfo.payFee/100).toString()+","+resultJson.attach]
                                             paramsMap << ["remark":GlobalConstant.getString("template.msg.pay.success.remark")]
                                             //paramsMap << ["color":""]
                                             def  result2=RequestRemoteHandler.postJson(GlobalConstant.getString("template.i2.url"),paramsMap,null,null)
                                             if (result2 == null)
                                                 logger.info("支付成功消息模板-发送消息失败请求失败[outTradeNo="+resultJson.out_trade_no+"]")
                                             else if ("00" == result2['respCode']) {
                                                 logger.info("支付成功消息模板-发送消息成功[outTradeNo="+resultJson.out_trade_no+"]")
                                             }else{
                                                 logger.info("支付成功消息模板-发送消息失败请求失败[outTradeNo="+resultJson.out_trade_no+",errorInfo="+result2['errorInfo']+"]")
                                             }
                                         }
                                         respString = "success";
                                     }
                                 }
                             }
                         }
                     }
                 }
            } catch (Exception ex) {
                logger.error("================支付返回结果出现异常===================：",ex)
            }
        }
        return respString;
    }

    void setNoticeToLs(TPay pay,String out_trade_no){
        //调用广电的支付账单通知接口
        logger.info("传入参数:out_trade_no:"+out_trade_no+"|智能卡号:"+pay.intelligentNo+"|金额:"+pay.totalFee+"|产品编号:"+pay.reserve1+"|长度："+pay.reserve2)
        int k = 3;
        ResultVo resultVo;
        for (int i = 0; i < k; i++) {//重试三次
            CalculatorDelegate calculatorDelegate= CalculatorHandler.getCalculatorPort();
            //获取客户编号
            List<UserCardCtmCardRltVo> userCardCtmCardRltVoList=calculatorDelegate.getUserCardCtmCardAll(pay.intelligentNo);
            List<ResultVo> list=calculatorDelegate.wxChargePdt(out_trade_no,pay.intelligentNo,pay.totalFee,pay.reserve1,pay.reserve2,"1",GlobalConstant.getString("GdOperator"));
            if(list!=null && list.size()>0){
                resultVo=list.get(0) as ResultVo;
                 break;
            }else{

            }
        }
        if (resultVo.result == null || "".equals(resultVo.result)) {
            return;
        }
        logger.info("广电返回报文:"+resultVo.nptabid+"|"+resultVo.result+"|"+resultVo.resultMsg)
        Map<String, Object> params = new HashMap<>()
        params << [outTradeNo: out_trade_no]//根据返回的商户号进行业务更新
        List<TOrder> orderList = orderService.findListByParams(params, null)
        if (orderList != null && orderList.size() > 0) {
            TOrder orderInfo= orderList.get(0)
            Long orderId = orderInfo.id
            //根据订单表中的userid去查询用户表数据获取openId、用于发送成功/失败消息
            def params2=[:]
            if(GlobalConstant.getString("mch_id").equals("7551000001")){
                pay.openId=orderInfo.reserve2
            }
            params2<<[openid:pay.openId]
            TblWechatSubscribe tblWechatSubscribe=wechatSubService.findObj(params2) as TblWechatSubscribe
            if ("0".equals(resultVo.result)){
                //调用成功
                logger.info("================【广电受理账单号】===========" + resultVo.nptabid)
                //业务更新，成功通知
                orderInfo.gdResult =CommonConstant.PayResult.ResultSuccess.value
                orderInfo.gdInfo = ""
                orderInfo.gdSerialNo = resultVo.nptabid //广电返回的受理账单号

                orderService.modifyBasic(orderInfo);//再次更新代表缴费成功

                //支付成功发送支付结果
                String money = (orderInfo.payFee/100).toString()
                //发送模板消息-支付成功消息
                Map<String,String> paramsMap=[:];
                String url=GlobalConstant.getString("template.msgBasic.url");
                url=url.replaceAll("orderId1",orderInfo.id+"");
                url=url.replaceAll("openId2",pay.openId);
                paramsMap << ["mchtId":GlobalConstant.getString("i2_mchtId")]
                paramsMap << ["templateId":GlobalConstant.getString("template.msg.id")]
                    paramsMap << ["touser":pay.openId]
                paramsMap << ["url":url]//链接
                paramsMap << ["first":GlobalConstant.getString("template.msg.pay.success.first")]
                paramsMap << ["keyword":(orderInfo.payFee/100).toString()+","+orderInfo.goodsName]
                paramsMap << ["remark":GlobalConstant.getString("template.msg.pay.success.remark")]
                //paramsMap << ["color":""]
                def  result2=RequestRemoteHandler.postJson(GlobalConstant.getString("template.i2.url"),paramsMap,null,null)
                if (result2 == null)
                    logger.info("支付成功消息模板-发送消息失败请求失败[outTradeNo="+out_trade_no+"]")
                else if ("00" == result2['respCode']) {
                    logger.info("支付成功消息模板-发送消息成功[outTradeNo="+out_trade_no+"]")
                }else{
                    logger.info("支付成功消息模板-发送消息失败请求失败[outTradeNo="+out_trade_no+",errorInfo="+result2['errorInfo']+"]")
                }

            }else{
                //联收未收到付款金额，去调用退款接口
                orderInfo.gdResult = CommonConstant.PayResult.ResultFail.value;//代表 缴费失败
                orderInfo.gdInfo=resultVo.resultMsg//错误信息
                String outRefundNo = "ebj" + ("" + Math.random() * 10).substring(2)
                //resultJson.total_fee.toString() //resultJson.total_fee.toString()
                if(GlobalConstant.getString("mch_id").equals("7551000001")){
                    orderInfo.payFee=1L;
                }
                String resRez = PayMentApi.submitRefund(pay.openId, orderInfo.outTradeNo, orderInfo.transactionId, outRefundNo,orderInfo.payFee.toString(), orderInfo.payFee.toString(), "ORIGINAL")

                ObjectMapper omRefu = new ObjectMapper();
                omRefu.setDateFormat(new SimpleDateFormat("yyyyMMddHH:mm:ss"));
                omRefu.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                logger.info("退款接口返回数据：" + resRez)
                //进行业务订单更新
                PayRefuse fuseJson = omRefu.readValue(resRez, PayRefuse.class);
                if ("0".equals(fuseJson.result_code) && "0".equals(fuseJson.status)) {// 退款成功
                    /**
                     * 支付退款返回参数
                     * transaction_id 是 String(32) 威富通交易号。
                     商户订单号 out_trade_no 是 String(32) 商户系统内部的订单号
                     商户退款单号 out_refund_no 是 String(32) 商户退款单号
                     威富通退款单号 refund_id
                     退款渠道 refund_channel 是 String(16) ORIGINAL—原路退款，默认
                     BALANCE—退回到余额
                     退款金额 refund_fee 是 Int 退款总金额,单位为分,可以做部分退款
                     现金券退款金额，coupon_refund_fee
                     */
                    //更新订单处理失败，退单处理
                    orderInfo.gdInfo = ""
                    orderInfo.transactionId = fuseJson.transaction_id
                    orderInfo.outRefundNo = fuseJson.out_refund_no//退款单号--我们这边自己的
                    orderInfo.refundId = fuseJson.refund_id//支付返回的
                    orderInfo.refundChannel = fuseJson.refund_channel//退款渠道
                        orderInfo.refundFee = fuseJson.refund_fee==null?null:Long.parseLong(fuseJson.refund_fee) //退款金额
                    orderInfo.couponRefundFee = fuseJson.coupon_refund_fee==null?null:Long.parseLong(fuseJson.coupon_refund_fee)//现金券退款金额
                    orderInfo.payStatus = CommonConstant.PayStatus.RefundSuccess.value
                    orderInfo.payTime = DateUtil.time.time//退款时间
                    orderService.modifyBasic(orderInfo);//更新订单数据

                    //发送模板消息-退款消息
                    Map<String,String> paramsMap=[:];
                    String url=GlobalConstant.getString("template.msgBasic.url");
                    url=url.replaceAll("orderId1",orderInfo.id+"");
                    url=url.replaceAll("openId2",pay.openId);
                    paramsMap << ["mchtId":GlobalConstant.getString("i2_mchtId")]
                    paramsMap << ["templateId":GlobalConstant.getString("template.msgfail.id")]
                    paramsMap << ["touser":pay.openId]
                    paramsMap << ["url":url]//链接
                    paramsMap << ["first":GlobalConstant.getString("template.msg.pay.fail.first")]
                    paramsMap << ["keyword":(orderInfo.payFee/100).toString()+","+orderInfo.goodsName]
                    paramsMap << ["remark":GlobalConstant.getString("template.msg.pay.fail.remark")]
                    //paramsMap << ["color":""]
                    def  result2=RequestRemoteHandler.postJson(GlobalConstant.getString("template.i2.url"),paramsMap,null,null)
                    if (result2 == null)
                        logger.info("退款消息模板-发送消息失败请求失败[outTradeNo="+out_trade_no+"]")
                    else if ("00" == result2['respCode']) {
                        logger.info("退款消息模板-发送消息成功[outTradeNo="+out_trade_no+"]")
                    }else{
                        logger.info("退款消息模板-发送消息失败请求失败[outTradeNo="+out_trade_no+",errorInfo="+result2['errorInfo']+"]")
                    }

                }else{
                    //退款失败处理
                    orderInfo.gdInfo=fuseJson.err_msg//错误信息
                    orderInfo.payStatus = CommonConstant.PayStatus.RefundFail.value//退款失败
                    orderInfo.payTime = DateUtil.time.time//退款时间
                    orderService.modifyBasic(orderInfo);//更新订单数据

                    //发送模板消息-退款消息
                    Map<String,String> paramsMap=[:];
                    String url=GlobalConstant.getString("template.msgBasic.url");
                    url=url.replaceAll("orderId1",orderInfo.id+"");
                    url=url.replaceAll("openId2",pay.openId);
                    paramsMap << ["mchtId":GlobalConstant.getString("i2_mchtId")]
                    paramsMap << ["templateId":GlobalConstant.getString("template.msgfail.id")]
                    paramsMap << ["touser":pay.openId]
                    paramsMap << ["url":url]//链接
                    paramsMap << ["first":GlobalConstant.getString("template.msg.pay.fail.first")]
                    paramsMap << ["keyword":(orderInfo.payFee/100).toString()+","+orderInfo.goodsName]
                    paramsMap << ["remark":GlobalConstant.getString("template.msg.pay.fail.remark")]
                    //paramsMap << ["color":""]
                    def  result2=RequestRemoteHandler.postJson(GlobalConstant.getString("template.i2.url"),paramsMap,null,null)
                    if (result2 == null)
                        logger.info("退款消息模板-发送消息失败请求失败[outTradeNo="+out_trade_no+"]")
                    else if ("00" == result2['respCode']) {
                        logger.info("退款消息模板-发送消息成功[outTradeNo="+out_trade_no+"]")
                    }else{
                        logger.info("退款消息模板-发送消息失败请求失败[outTradeNo="+out_trade_no+",errorInfo="+result2['errorInfo']+"]")
                    }
                }
            }
        }
    }
}
